<script>
    const list = [
      {
        id: 1,
        pid: null,
        name: '销售部'
      }, {
        id: 2,
        pid: null,
        name: '运营部'
      }, {
        id: 3,
        pid: null,
        name: '总裁办'
      }, {
        id: 4,
        pid: 1,
        name: '北京销售部'
      },{
        id: 5,
        pid: 1,
        name: '上海销售部'
      }, {
        id: 6,
        pid: 2,
        name: '游戏运营部'
      }
    ]

    function list2Tree(list) {
      const map = list.reduce((sum, obj) => {
        const { id } = obj
        sum[id] = obj
        return sum
      }, {})
      return list.reduce((sum, obj) => {
        const { pid } = obj
        const parent = map[pid]
        if(parent) {
          (parent.children = parent.children || []).push(obj)
        }else {
          sum.push(obj)
        }
        return sum
      }, [])
    }

    console.log(list2Tree(list))
</script>